import axios from '../../plugins/axios';
import vueGlobal from '../../vueGlobal.js';
import storage from '../../utils/storage.js';
import indexView from './index.vue';
import { USER_INFO_KEY } from '../../config/index.js';
import { useUserInfoStore } from '../../pinia/userInfo.js';

function getAreaCode() {
  const userInfoStore = useUserInfoStore();
  return userInfoStore.area_code;
}

async function sendVideoZzPeople(params = {}) {
  // return await axios.postJson('/xw-dynamic/v1/webSocket/sendMsg', params);
  return await axios.get('/xw-microservice/xw-command-dispatch/v3/zz/people/sendVideoZzPeople', { params });
}

export function getVideoConferencingRoomId(area_code) {
  if (!area_code) {
    area_code = getAreaCode();
  }
  let code = String(area_code).substring(3);
  code = code.replace(/\./g, '');
  if (code == '5101081001') {
    //一里塘社区，房间号为自己，但是需要将前两位替换为9
    code = 9 + code.substring(2);
  } else if (code.length >= 8) {
    //其他账号，都是默认呼叫到街道
    code = code.substring(0, 8);
  }
  // return 51060301;
  return code;
}

export const showVideoConferencingDialog = (() => {
  let opened = false;
  /* options: { roomId, area_code } */
  return (options) => {
    if (opened) return;
    opened = true;
    let { roomId, area_code } = options || {};
    if (!area_code) {
      area_code = getAreaCode();
    }
    vueGlobal.get('$dialog')({
      content: indexView,
      contentProps: { roomId, areaCode: area_code },
      dialogProps: {
        title: '综合调度指挥连线',
        width: 'max',
        height: 'fixed',
        mask: false,
        footer: null,
        afterClose() {
          opened = false;
        },
        bodyStyle: {
          background: '#020A11',
          overflow: 'hidden',
          padding: 0,
        },
      },
    });
  };
})();

export async function callVideoConferencing(option) {
  option = Object.assign({}, option);
  const params = {
    account: option.account,
    people_name: option.name,
    room_num: option.roomId,
  };
  if (!params.account) {
    vueGlobal.get('$message').error('被呼叫账号不能为空');
    return false;
  }
  if (!params.people_name) {
    vueGlobal.get('$message').error('被呼叫账号名称不能为空');
    return false;
  }
  if (!params.room_num) {
    vueGlobal.get('$message').error('房间号不能为空');
    return false;
  }
  const userInfo = storage.session.getItem(USER_INFO_KEY);
  const wsParams = {
    cmd: 'videoconferencing',
    sid: option.account,
    is_jpush: 1,
    data: {
      type: 'call',
      from_name: userInfo.nickname,
      from_sid: userInfo.uuAccount,
      room_number: getVideoConferencingRoomId(userInfo.areaCode),
    },
  };
  try {
    // 发送websocket消息
    vueGlobal.get('$vbus').$emit('sendSocketMsg', wsParams);
    const res = await sendVideoZzPeople(params).catch(() => {});
    if (res && res.code === 200) {
      vueGlobal.get('$message').success('发送成功,等待对方接听');
    } else {
      vueGlobal.get('$message').error('呼叫失败,请稍后再次尝试!');
      return Promise.reject();
    }
  } catch (e) {
    vueGlobal.get('$message').error('呼叫失败,请稍后再次尝试!');
    return Promise.reject();
  }
}

export async function sendVideoConferencingMsg(account, msg) {
  const params = {
    cmd: 'videoconferencing',
    sid: account,
    data: { type: 'answer', msg: msg },
  };
  vueGlobal.get('$vbus').$emit('sendSocketMsg', params);
  await sendVideoZzPeople(params);
}

export async function handleVideoConferencing(account, option = {}) {
  const { type, handle } = option;
  const thEnum = {
    audio: { open: 'open_audio', close: 'close_audio' },
    video: { open: 'open_video', close: 'close_video' },
  };
  const params = {
    cmd: 'videoconferencing',
    sid: account,
    data: { type: thEnum[type][handle] },
  };
  // 发送websocket消息
  vueGlobal.get('$vbus').$emit('sendSocketMsg', params);
  await sendVideoZzPeople(params);
}
